from rest_framework import generics, status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.db import transaction
from .models import Card, UserCard
from .serializers import CardSerializer, UserCardSerializer, CardPurchaseSerializer


class CardListView(generics.ListAPIView):
    """获取所有卡牌列表"""
    serializer_class = CardSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        queryset = Card.objects.filter(is_active=True)
        
        # 搜索功能
        search = self.request.query_params.get('search', None)
        if search:
            queryset = queryset.filter(name__icontains=search)
        
        # 星级筛选
        star_level = self.request.query_params.get('star_level', None)
        if star_level:
            queryset = queryset.filter(star_level=star_level)
        
        # 属性筛选
        element = self.request.query_params.get('element', None)
        if element:
            queryset = queryset.filter(element=element)
        
        # 稀有度筛选
        rarity = self.request.query_params.get('rarity', None)
        if rarity:
            queryset = queryset.filter(rarity=rarity)
        
        return queryset.order_by('-created_at')


class CardDetailView(generics.RetrieveAPIView):
    """获取卡牌详情"""
    queryset = Card.objects.filter(is_active=True)
    serializer_class = CardSerializer
    permission_classes = [permissions.IsAuthenticated]


class UserCardListView(generics.ListAPIView):
    """获取用户拥有的卡牌"""
    serializer_class = UserCardSerializer
    permission_classes = [permissions.IsAuthenticated]
    
    def get_queryset(self):
        return UserCard.objects.filter(user=self.request.user).order_by('-obtained_at', 'id')


@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def buy_card(request):
    """购买卡牌"""
    serializer = CardPurchaseSerializer(data=request.data)
    if serializer.is_valid():
        card_id = serializer.validated_data['card_id']
        quantity = serializer.validated_data['quantity']
        
        try:
            card = Card.objects.get(id=card_id, is_active=True)
        except Card.DoesNotExist:
            return Response({'error': '卡牌不存在'}, status=status.HTTP_400_BAD_REQUEST)
        
        total_cost = card.cost * quantity
        
        if request.user.coins < total_cost:
            return Response({'error': '游戏币不足'}, status=status.HTTP_400_BAD_REQUEST)
        
        with transaction.atomic():
            # 扣除游戏币
            request.user.coins -= total_cost
            request.user.save()
            
            # 添加卡牌到用户库存
            user_card, created = UserCard.objects.get_or_create(
                user=request.user,
                card=card,
                defaults={'quantity': quantity}
            )
            if not created:
                user_card.quantity += quantity
                user_card.save()
        
        return Response({
            'message': '购买成功',
            'user_coins': request.user.coins,
            'card': CardSerializer(card).data
        })
    
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
